<?php
use models\dao\ObservatorioDAO;
use Doctrine\Common\Cache\ArrayCache;
use models\dao\UsuarioDAO;
use models\dao\ImagemDAO;
use models\Imagem;

class Image extends CI_Controller {

	private $imageDAO;
	private $userDAO;
	private $observatorioDAO;
	private $em;
	private $user;

	private static $TEMP_PATH = 'files/images/temp/';
	private static $PATH = 'files/images/';

	private static $MONTH_CODE = array(
		1 => 'A',
		2 => 'B',
		3 => 'C',
		4 => 'D',
		5 => 'E',
		5 => 'F',
		6 => 'G',
		7 => 'H',
		8 => 'I',
		9 => 'J',
		10 => 'L',
		11 => 'M',
		12 => 'N'
	);

	public function __construct() {
		parent::__construct();

		$this->load->library('zip');

		$this->em = $this->doctrine->em;
		$this->userDAO = new UsuarioDAO($this->em);
		$this->imageDAO = new ImagemDAO($this->em);
		$this->observatorioDAO = new ObservatorioDAO($this->em);

		$currentUser = $this->session->userdata('user');
		$this->user = $this->userDAO->findByPrimaryKey($currentUser['id']);

	}

	public function findAll() {

		if (!isset($_GET['from_date'])) {
			$images = $this->imageDAO->findAll($this->user);
		} else {
			$from = isset($_GET['from_date']) ? $_GET['from_date'] : NULL;
			$to = isset($_GET['to_date']) ? $_GET['to_date'] : NULL;
			$type = isset($_GET['type']) ? $_GET['type'] : NULL;
			$obs = isset($_GET['observatory']) ? $_GET['observatory'] : NULL;

			$images = $this->imageDAO->find($from, $to, $type, $obs);
		}

		$result['result'] = array();

		foreach ($images as $image) {
			array_push($result['result'], $image->toArray());
		}

		echo json_encode($result);

	}

	public function upload() {

		$file = $_FILES['Filedata'];

		$imageName = $file['name'];

		$imagePath = self::$TEMP_PATH . $imageName;


		if (move_uploaded_file($file['tmp_name'], $imagePath)) {
			$array['success'] = true;
		} else {
			$array['success'] = false;
		}

		echo json_encode($array);
	}

	public function delete() {
		$data = (array) json_decode($_POST['data']);

		$image = $this->imageDAO->findByPrimaryKey($data['id']);

		@unlink($image->getCaminho());

		$this->imageDAO->delete($image);

		$result['success'] = true;
		echo json_encode($result);
	}

	public function update() {
		$data = (array) json_decode($_POST['data']);

		$image = $this->imageDAO->findByPrimaryKey($data['id']);
		$image->setNome($data['nome']);
		$image->setTipo($data['tipo']);

		$this->imageDAO->save($image);

		$result['success'] = true;

		echo json_encode($result);
	}

	private function getImageName($tipo) {
		$ano =  date('Y');
		$mes = self::$MONTH_CODE[date('m')];
		$hora = date('H');
		$minuto = date('i');
		$segundo = date('s');

		$nome = $ano . $mes . $hora . $minuto . '_' . rand() . '_' . $tipo;
		return $nome;
	}

	public function download() {
		$images = explode("|", $_GET['param']);

		foreach ($images as $image) {
			$this->zip->add_data($image, file_get_contents($image));
		}

		$this->zip->download('images.zip');
	}

	public function saveImages($tipo, $obs) {

		$obs = $this->observatorioDAO->findByPrimaryKey($obs);

		$handle = opendir(self::$TEMP_PATH);
		while ($file = readdir($handle)) {
			if ($file != '.' && $file != '..') {

				$extension = explode('.', $file);

				$oldName = $file;
				$newName = $this->getImageName($tipo) . '.' . $extension[1];

				rename(self::$TEMP_PATH . $oldName, self::$PATH . $newName);

				try {
					$image = new Imagem();
					$image->setCaminho(self::$PATH . $newName);
					$image->setNome($newName);
					$image->setTipo($tipo);
					$image->setUsuario($this->user);
					$image->setObservatorio($obs);

					$this->imageDAO->save($image);
				} catch (Exception $e) {
					echo false;
					return;
				}

			}
		}

		echo true;
	}



}

